package com.zat.mes.andrmes.dofun.main

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.love.zywanandroid.enums.BottomTab
import com.love.zywanandroid.fragment.HomeFragment
import com.love.zywanandroid.fragment.MeFragment
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.main.vm.ApkModel
import com.zat.mes.andrmes.dofun.qualitytest.OnSiteActivity
import com.zat.mes.andrmes.dofun.work.DayProducePlanAndMaterialUsedActivity
import com.zat.mes.andrmes.dofun.work.MotorWorkRecordActivity
import com.zat.mes.andrmes.dofun.work.UpdatePackQtyActivity
import com.zat.mes.andrmes.event.QrcodeEventMessage
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionCode.Companion.INSTALL_CODE_MAIN
import com.zat.mes.andrmes.global.CompanionCode.Companion.INSTALL_CODE_ME
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.service.PollService
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.StatusBarUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.UpdateManager
import kotlinx.android.synthetic.main.bottom_view.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import permissions.dispatcher.*

/**
 * 主页activity
 */
@RuntimePermissions
class MainActivity : BaseActivity() {
    /**
     * apk更新model
     */
    var apkModel: ApkModel? = null
    var updateManager: UpdateManager? = null
    private lateinit var homeFragment: HomeFragment
    private lateinit var meFragment: MeFragment
    private lateinit var thisFragment: Fragment
    private var requestCode: Int = 0
    override fun init() {
        setContentView(R.layout.activity_main)

        homeFragment = HomeFragment()
        meFragment = MeFragment()
        thisFragment = Fragment()
        swichFragment(homeFragment)
        bottombar.setListener {
            when (it) {
                BottomTab.HOME -> swichFragment(homeFragment)
                BottomTab.ME -> swichFragment(meFragment)
            }
        }
        loadModel()
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        var empId = loginResultBean.empid
        PollService.startPollService(this,empId.toString())

        //startActivity(Intent(this, DayProducePlanAndMaterialUsedActivity::class.java))
       // startActivity(Intent(this, MotorWorkRecordActivity::class.java))
       // startActivity(Intent(this, UpdatePackQtyActivity::class.java))

    }

    /**
     * 加载loadmodel
     */
    private fun loadModel() {
        apkModel = ViewModelProvider(this).get(ApkModel::class.java)
        apkModel?.getApkBean()?.observe(this, Observer {
            closeLoading()
            if (it == null) {
//                showToast("当前是最新版本")
            } else {
                //显示下载
                AlertDialog.Builder(this)
                    .setMessage(getString(R.string.find_new_version))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setPositiveButton(
                        getString(R.string.sure),
                        DialogInterface.OnClickListener { dialog, which ->
                            updateManager = UpdateManager(this, it.fileUrl, 200);
                        })
                    .show()
            }
        })
        checkMainAppVerWithPermissionCheck()
    }

    override fun setStatusBar() {
//        var drawble = resources.getDrawable(R.drawable.dw_statusbar);
//        StatusBarUtils.with(this).setDrawable(drawble).init()
        StatusBarUtils.fullScreen(this)
    }

    /**
     * 切换fragment
     */
    fun swichFragment(fragment: Fragment) {
        val beginTransaction = supportFragmentManager.beginTransaction()
        if (fragment != thisFragment) {
            if (!fragment.isAdded) {
                beginTransaction.hide(thisFragment)
                    .add(R.id.framContener, fragment)
                    .commitAllowingStateLoss()

            } else {
                beginTransaction.hide(thisFragment).show(fragment)
                    .commitAllowingStateLoss()
            }
            thisFragment = fragment
        }
    }

    /**
     * 开启相关权限
     */
    fun showCameraWithPermission(code: Int) {
        //开启权限 跳转二维码扫描页面
        requestCode = code
        showCameraWithPermissionCheck()
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), requestCode)
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
            if (requestCode == CompanionCode.REQUEST_EMP_CH_QR_CODE) {
                //普通扫码
//                if (qrCode != null) {
//                    if (qrCode?.startsWith(CompanionType.STRING_QR_MAC)) {
//                        //人员设备绑定
//                        homeFragment.loadBindMachine(qrCode)
//                    }
//                }

            } else if (requestCode == CompanionCode.REQUEST_QC_PLAN_QR_CODE) {
                //质检
                val intentOnRecord = Intent(this, OnSiteActivity::class.java)
                intentOnRecord.putExtra(CompanionType.INTENT_EXTRA_QRCODE, qrCode)
                //0 质检 1 巡检
                intentOnRecord.putExtra(CompanionType.INTENT_EXTRA_QCTYPE, 0)
                startBaseActivity(intentOnRecord)
            } else if (requestCode == CompanionCode.REQUEST_ON_SITE_QR_CODE) {
                //巡检
                val intentOnSite = Intent(this, OnSiteActivity::class.java)
                intentOnSite.putExtra(CompanionType.INTENT_EXTRA_QRCODE, qrCode)
                //0 质检 1 巡检
                intentOnSite.putExtra(CompanionType.INTENT_EXTRA_QCTYPE, 1)
                startBaseActivity(intentOnSite)
            }

        }
        if (requestCode == INSTALL_CODE_MAIN) {
            //8.0 安装未知权限问题
            updateManager?.resultInstall()
        } else if (requestCode == INSTALL_CODE_ME) {
            //8.0 安装未知权限问题
            meFragment.installApk()
        }
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }

    /**
     * 打开二维码扫描
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onQrcodeEvent(event: QrcodeEventMessage?) {
        event?.message?.let { showCameraWithPermission(it) };
    }

    //======== app 版本更新====//
    @NeedsPermission(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun checkMainAppVer() {
        showLoading()
        apkModel?.loadCheckVersion(
            packageManager?.getPackageInfo(
                packageName,
                0
            )?.versionCode.toString()
        )
    }

    @OnShowRationale(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun showMainRationale(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun onMainDenied() {
        checkMainAppVerWithPermissionCheck()
    }

    @OnNeverAskAgain(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun onMainNeverAskAgain() {
//        showToast("请到设置打开存储权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    override fun onDestroy() {
        stopService(Intent(this,PollService::class.java))
        super.onDestroy()
    }
}
